package org.argus.job.work.gateway.loadbalancer;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.argus.job.common.constants.HeaderConstants;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.*;
import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.core.RoundRobinLoadBalancer;
import org.springframework.cloud.loadbalancer.core.SelectedInstanceCallback;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 根据Worker Header IP 来选择Worker实例
 * 
 * @Author 刘文/Cliff Liu
 * @Date 2024/9/16
 */
@Slf4j
public class WorkerIPHeaderLoadBalancer extends RoundRobinLoadBalancer {

    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider;

    public WorkerIPHeaderLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider,
        String serviceId) {
        super(serviceInstanceListSupplierProvider, serviceId);
        this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        List<String> workerIps = ((RequestDataContext)request.getContext()).getClientRequest().getHeaders()
                .get(HeaderConstants.WORKER_IP_HEADER_NAME);
        // 没有worker ip，使用轮询
        if (CollectionUtil.isEmpty(workerIps)) {
            return super.choose(request);
        }
        String workerIp = workerIps.get(0);
        ServiceInstanceListSupplier supplier =
            serviceInstanceListSupplierProvider.getIfAvailable(NoopServiceInstanceListSupplier::new);
        return supplier.get(request).next()
            .map(serviceInstances -> processInstanceResponse(supplier, serviceInstances, workerIp));
    }

    private Response<ServiceInstance> processInstanceResponse(ServiceInstanceListSupplier supplier,
        List<ServiceInstance> serviceInstances, String workerIp) {
        Response<ServiceInstance> serviceInstanceResponse = getInstanceResponse(serviceInstances, workerIp);
        if (supplier instanceof SelectedInstanceCallback && serviceInstanceResponse.hasServer()) {
            ((SelectedInstanceCallback)supplier).selectedServiceInstance(serviceInstanceResponse.getServer());
        }
        return serviceInstanceResponse;
    }

    private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> serviceInstances, String workerIp) {
        for (ServiceInstance serviceInstance : serviceInstances) {
            if (workerIp.equals(serviceInstance.getHost())) {
                return new DefaultResponse(serviceInstance);
            }
        }
        if (log.isWarnEnabled()) {
            log.warn("No server available for worker ip : " + workerIp);
        }
        return new EmptyResponse();
    }
}
